package cn.aitrox.ry.service.image.service.impl;

import cn.aitrox.ry.bean.RespResult;
import cn.aitrox.ry.service.image.dao.ImageDao;
import cn.aitrox.ry.service.image.dao.ImageInfoDao;
import cn.aitrox.ry.service.image.dto.image.in.ImageQueryInDto;
import cn.aitrox.ry.service.image.dto.image.out.ImageInfoOutDto;
import cn.aitrox.ry.service.image.entity.ImageInfoMongoEntity;
import cn.aitrox.ry.service.image.entity.ImageMongoEntity;
import cn.aitrox.ry.service.image.service.ImageService;
import cn.aitrox.ry.util.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private ImageInfoDao imageInfoDao;

    @Override
    public RespResult<List<ImageInfoOutDto>> query(ImageQueryInDto input) {
        List<String> modeList = null;
        if (ArrayUtil.isEmpty(input.getTransferModeEnums())) {
            modeList = input.getTransferModeEnums().stream().map(x -> x.getMode()).distinct().collect(Collectors.toList());
        }
        List<ImageInfoMongoEntity> imageInfoList = imageInfoDao.query(input.getGroups(), input.getGroupTypeEnum().getGroupType(), modeList);

        if (ArrayUtil.isEmpty(imageInfoList)) {
            return RespResult.ok();
        }

        List<ImageInfoOutDto> list;
        if (!input.getQueryImage()) {
            list = imageInfoList.stream().map(x -> new ImageInfoOutDto(x, null)).collect(Collectors.toList());
        } else {
            List<ImageMongoEntity> imageList = imageDao.query(input.getGroups(), input.getGroupTypeEnum().getGroupType(), modeList, input.getNumbers());
            list = imageInfoList.stream().map(x -> {
                List<ImageMongoEntity> filterImages = imageList.stream().filter(y -> y.getGroup().equals(x.getGroup()) && y.getGroupType().equals(x.getGroupType()) && y.getMode().equals(x.getMode())).collect(Collectors.toList());
                return new ImageInfoOutDto(x, filterImages);
            }).collect(Collectors.toList());
        }

        return RespResult.ok(list);
    }


}
